package com.juyu.miliao.api.controller;

import com.juyu.miliao.api.domain.OfficialQuestionToAnswerInfo;
import com.juyu.miliao.api.service.OfficialQuestionToAnswerService;
import com.juyu.miliao.common.domain.Subject;
import com.juyu.miliao.common.exception.ConsumeRuntimeException;
import com.juyu.miliao.common.exception.IllegalParamException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author xuanqicheng
 * @create 2018-18-10:42 AM
 */
@RestController
@RequestMapping("/officialAnswer")
public class OfficialQuestionToAnswerController {

    @Autowired
    private OfficialQuestionToAnswerService officialQuestionToAnswerService;

    /**
     * 回答官方问题
     */
    @PostMapping("/create")
    public void createOfficialQuestionToAnswer(Authentication token,
                                               OfficialQuestionToAnswerInfo officialQuestionToAnswerInfo){
        Subject subject = (Subject) token.getPrincipal();

        officialQuestionToAnswerInfo.setAnswerUserId(subject.getId());

        //判断是否回答过，如果回答过不与添加
        boolean bl = officialQuestionToAnswerService
                .checkQuestionAnsweringByOfficialQuestionIdAndAnswerUserId(officialQuestionToAnswerInfo);
        if(bl){
            throw  new ConsumeRuntimeException("此用户回答过这个官方问题");
        }


        officialQuestionToAnswerService.createInfo(officialQuestionToAnswerInfo);
    }

    @PostMapping("/eavesdropping")
    public void updateEavesdroppingNumber(Authentication token,
                                          OfficialQuestionToAnswerInfo officialQuestionToAnswerInfo){
        Subject subject = (Subject) token.getPrincipal();

        if(officialQuestionToAnswerInfo.getId()==null){
            throw  new ConsumeRuntimeException("id不能为空");
        }
        OfficialQuestionToAnswerInfo obj = officialQuestionToAnswerService
                .selectOfficialAnswerById(officialQuestionToAnswerInfo.getId());

        if(obj!=null && subject.getId() != obj.getAnswerUserId()){
            officialQuestionToAnswerService.updateEavesdroppingNumber(obj,subject.getId());
        }


    }
}
